/**
 * 
 */
package com.example.myproject.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.utils.SerializationUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * 
 */
public class FileUtil {

	protected final static Log log = LogFactory.getLog(FileUtil.class);

	public static String UTF8="UTF-8";

	public static String processLogger(Throwable throwable) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		throwable.printStackTrace(pw);
		pw.flush();
		sw.flush();
		return sw.toString();
	}

	/**
	 * 使用文件通道的方式复制文件
	 * @param target
	 *            复制到的新文件
	 */
	public static boolean fileChannelCopy(File source, File target) {
		if(!source.exists()){
			System.out.println("源文件不存在！");
			return false;
		}
		File targetPath = new File(target.getParent());
		if(!targetPath.exists()){
			targetPath.mkdirs();
		}
		try {
			FileInputStream fileInputStream = new FileInputStream(source);
			FileOutputStream fileOutputStream = new FileOutputStream(target);
			FileChannel fileChannelIn = fileInputStream.getChannel();// 得到对应的文件通道
			FileChannel fileChannelOut = fileOutputStream.getChannel();// 得到对应的文件通道
			fileChannelIn.transferTo(0, fileChannelIn.size(), fileChannelOut);// 连接两个通道，并且从in通道读取，然后写入out通道
			// 人走带门
			fileInputStream.close();
			fileChannelIn.close();
			fileOutputStream.close();
			fileChannelOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("复制完毕！");
		return true;
	}


	/**
	 * 下载网络文件到本地
	 * @param netUrl 网络文件源
	 * @param localFolder
	 * @param localFileName
	 * @throws java.net.MalformedURLException
	 */
	public static void downloadNet(String netUrl , String localFolder , String localFileName) throws MalformedURLException {
		// 下载网络文件
		int byteread = 0;
		URL url = new URL(netUrl);
		URLConnection conn = null ;
		InputStream inStream = null;
		FileOutputStream fs = null ;
		try {
			File dirFile = new File(localFolder);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			conn = url.openConnection();
			inStream = conn.getInputStream();
			File imgFile = new File(localFolder + "/" + localFileName);
			if(imgFile.exists()){
				imgFile.delete();
			}
			fs = new FileOutputStream(localFolder + "/" + localFileName);

			byte[] buffer = new byte[1204];
			while ((byteread = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
			}
			fs.close();
		} catch (FileNotFoundException e) {
			log.info(e);
		} catch (IOException e) {
			log.info(e);
		}finally {
			if(inStream != null){
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fs != null){
				try {
					fs.close();
				} catch (IOException e) {
					log.info(e);
				}
			}
		}
	}

	/**
	 * 验证文件夹是否存在，如果不存在，从最开始创建
	 * @param fileFolder
	 */
	public static void validateFolder(String fileFolder) {
		// /usr/local/1jia2/upload/photo/
		// d:/1jia2/upload/photo/
		String[] folders = fileFolder.split("/");
		StringBuilder folder = new StringBuilder(folders[0]);
		for (int i = 1;i < folders.length;i++) {
			folder.append("/").append(folders[i]);
			File file = new File(folder.toString());
			if (!file.exists()) {
				file.mkdir();
			}
		}
	}

	/**
	 * 读取文件内容
	 *
	 * @param filePath 待读取文件完整路径
	 * @return
	 */
	public static String readFileData(String filePath) throws Exception {
		System.out.println("开始读取数据,文件路径 = " + filePath);
		File file = new File(filePath);
		if (file.exists()) {
			StringBuilder result = new StringBuilder();
			try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
				String s = null;
				int i = 1;
				//使用readLine方法，一次读一行
				while ((s = br.readLine()) != null) {
					result.append(s + System.lineSeparator());
					System.out.println("已读取" + (i++) + "行");
				}
			} catch (Exception e) {
				System.err.println(e);
				throw e;
			}
			System.out.println("文件读取完毕，路径 = " + filePath);
			return result.toString();
		} else {
			throw new RuntimeException("文件不存在，请检查！");
		}
	}


	/**
	 *
	 * @param file
	 * @return
	 */
	public static List<String> readTxt(File file) {
		List<String> txtlist = new ArrayList<String>();
		try {
			String encoding = "UTF-8";
			if (file.isFile() && file.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTXT = null;
				while ((lineTXT = bufferedReader.readLine()) != null) {
					txtlist.add(lineTXT.toString().trim());
				}
				read.close();
			} else {
				System.out.println("The File doesn't exist");
			}
		} catch (Exception e) {
			log.error(e);
		}
		return txtlist;
	}

	public static void writeTxt(String fileName, String contents) {
		try {
			FileWriter fstream = new FileWriter(fileName);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(contents);
			out.close();
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		}
	}

    public static void writeProcessId(String fileName, String contents) {
        try {
            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            //将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(contents);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	/**把一个文件读入到一个字符串里面,适合小文件,chains*/
	public static String getContentByFileName(String fullPathFileName)
	{
	    String str="";
	    File file=new File(fullPathFileName);
	    try {
	        FileInputStream in=new FileInputStream(file);
	        // size  为字串的长度 ，这里一次性读完
	        int size=in.available();
	        byte[] buffer=new byte[size];
	        in.read(buffer);
	        in.close();
	        str=new String(buffer,"UTF-8");
	    } catch (IOException e) {
	    	e.printStackTrace();
	        return null;
	    }
	    return str;

	}


	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 * @return boolean
	 */
	public static File findFileByFileName(String fromPath,String findFileName) {
			File file = new File(fromPath);
			String[] filelist = file.list();
		    File destFile = null;
			for (int i = 0; i < filelist.length; i++) {
				System.out.println("文件："+filelist[i]);
				File temp = new File(fromPath + "\\" + filelist[i]);
				if(temp.isDirectory()){
					//回掉处要返回结果回来
					destFile = findFileByFileName(temp.getAbsolutePath(),findFileName);
					if(destFile!=null){
						return destFile;
					}

				}else{
					if((findFileName+".java").equals(temp.getName())){
						destFile = temp;
						if(destFile!=null){
							return destFile;
						}
					}
				}
			}
		return destFile;
	}

	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 *
	 * @param delpath
	 *            String
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 * @return boolean
	 */
	public static boolean deleteFolder(String delpath) {
		try {
			File file = new File(delpath);
			// 当且仅当此抽象路径名表示的文件存在且 是一个目录时，返回 true
			if (!file.isDirectory()) {
				 file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				if(filelist!=null){
					for (int i = 0; i < filelist.length; i++) {
						File delfile = new File(delpath + "\\" + filelist[i]);
						if (!delfile.isDirectory()) {
							delfile.delete();
						} else if (delfile.isDirectory()) {
							deleteFolder(delpath + "\\" + filelist[i]);
						}
					}
				}
				file.delete();//删除自己的空文件夹，因为下面没子
			}
		} catch (Exception e) {
			System.out.println("deletefile() Exception:" + e.getMessage());
		}
		return true;
	}

	//删除文件和文件夹
	public static void deleteFolder(File file){
		if(!file.exists()){
			System.out.println("deleteFolder==");
			return;
		}
		if(file.isFile() ||  file.list().length==0){
			file.delete();
		}else{
			File[] files = file.listFiles();
			if(files!=null){
				for(int i=0;i<files.length;i++){
					deleteFolder(files[i]);
					files[i].delete();
				}
			}
		}
	}

	public static void writeObject(String path,Object object){
		try {
			File file = new File(path);
//			if(file.isFile() && !file.exists()){
//				file.createNewFile();
//			}
			FileOutputStream f = new FileOutputStream(file);
			ObjectOutputStream s = new ObjectOutputStream(f);
			;
			s.writeObject(object);

			//s.write(SerializationUtils.serialize(object));
			s.flush();
			s.close();
			f.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public static void writeObjectBySpring(String path,Object object){
		try {
			File file = new File(path);
//			if(file.isFile() && !file.exists()){
//				file.createNewFile();
//			}
			FileOutputStream f = new FileOutputStream(file);
			byte[] s = SerializationUtils.serialize(object);
			f.write(s,0,s.length);
			f.flush();
			f.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Object readObjectBySpring(String path){
		Object temp=null;
		File file =new File(path);

			FileInputStream in = null;
			try {
				in = new FileInputStream(file);
//				ByteArrayOutputStream bos = new ByteArrayOutputStream();
//				int buf_size = 1024;
//				byte[] buffer = new byte[buf_size];
//				int len = 0;
//				while (-1 != (len = in.read(buffer, 0, buf_size))) {
//					//bos.write(buffer, 0, len);
//				}
////				ByteArrayOutputStream output = new ByteArrayOutputStream();
//				int b;
//				// 从文件读取数据，并写入到内存缓冲区中
//				while((b = in.read()) > 0) {
//					output.write(b);
//				}
				ObjectInputStream objIn = new ObjectInputStream(in);
				temp = SerializationUtils.deserialize(objIn);

				//temp = SerializationUtils.deserialize(output.toByteArray());
				in.close();
			System.out.println("read object success!");
		} catch (IOException e) {
			System.out.println("read object failed");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return temp;
	}



	//对象实现了序列化，但是重新反序列化加了属性会报错吗，
	public static Object readObject(String path){
		Object temp=null;
		File file =new File(path);
		FileInputStream in;
		try {
			in = new FileInputStream(file);
			ObjectInputStream objIn=new ObjectInputStream(in);
			temp = objIn.readObject();
			objIn.close();
			System.out.println("read object success!");
		} catch (IOException e) {
			System.out.println("read object failed");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return temp;
	}

	/*转换房介通的解密房客源业主和客户信息
	* @author chains
	* */
	public static void transformFjtOwnerOrCustomerFile(String dbName,String fromFileName,String toFileName){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").split("\t");
					//strListContacts.append("insert into tb_Decode_proCusContacts values("+"'"+listContacts.get(i).replace("'","").replace(";","").replace("\t","','")+"'"+");").append("\n");
					StringBuffer strsB=new StringBuffer("");
					if(strs!=null&&strs.length>0){
						strsB.append("update "+(dbName)+".dbo.com_contact set name=(case when contactType='owner' then '").append(strs.length>=2?strs[1]+"'":"'").append(" else name end),phone1='").append(strs.length >= 3 ? strs[2] + "'" : "'").append(" where contactType in ('owner','customer') and contactUuid='").append(strs.length>=1?strs[0]+"'":"'").append(";\n");
					}
					strListContacts.append(strsB);
				}
			}
			writeTxt(toFileName, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}

	/*转换房介通的解密房源联系人信息
	* @author chains
	* */
	public static void transformFjtNonOwnerFile(String dbName,String fromFileName,String toFileName){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";", "").split("\t");
					//strListContacts.append("insert into tb_Decode_proCusContacts values("+"'"+listContacts.get(i).replace("'","").replace(";","").replace("\t","','")+"'"+");").append("\n");
					StringBuffer strsB=new StringBuffer("");
					if(strs!=null&&strs.length>0){
						strsB.append("update " + (dbName) + ".dbo.com_contact set name='").append(strs.length>=2?strs[1]+"'":"'").append(",phone1='").append(strs.length>=3?strs[2]+"'":"'").append(" where contactType='non-owner' and contactUuid='").append(strs.length>=1?strs[0]+"'":"'").append(";\n");
					}
					strListContacts.append(strsB);
				}
			}
			writeTxt(toFileName, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}

	/*转换房介大师的解密房源业主信息
	* @author chains
	* */
	public static void transformFjdsOwnerFile(String dbName,String fromFileName,String toFileName){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").replace(" ","").trim().split(",");
					StringBuffer strsB=new StringBuffer("");
					if(strs!=null&&strs.length>0){
						//strsB.append("update " + (dbName) + ".dbo.com_contact set name='").append(strs.length>=8?strs[7]+"'":"'").append(",phone1='").append(strs.length>=1?strs[0]+"'":"'").append(",phone2=('" + (strs.length >= 7? strs[6]:"")+"'+'").append(strs.length >= 12 ? (!strs[6].equals("")&&!strs[11].equals("")?" "+strs[11]:strs[11]) + "'":"'").append(") where contactType ='owner' and contactUuid='").append(strs.length>=2?strs[1]+"'":"'").append(";\n");
						strsB.append("update " + (dbName) + ".dbo.com_contact set name='").append(strs.length >= 8 ? (strs[7]).replace(" ", "").trim() + "'" : "'").append(",phone1='").append(strs.length>=1?strs[0].replace(" ","").trim()+"'":"'").append(",phone2=('" + (strs.length >= 12? strs[11].replace(" ","").trim()+"'":"'")).append(") where contactType ='owner' and contactUuid='").append(strs.length>=6?strs[1]+strs[5]+"'":"'").append(";\n");
				}
					strListContacts.append(strsB);
				}
			}
			writeTxt(toFileName, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}

	/*转换房介大师的解密客源客户信息
	* @author chains
	* */
	public static void transformFjdsCustomerFile(String dbName,String fromFileName,String toFileName){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").replace(" ","").trim().split(",");
					StringBuffer strsB=new StringBuffer("");
					if(strs!=null&&strs.length>0){
						//strsB.append("update " + (dbName) + ".dbo.com_contact set name='").append(strs.length>=8?strs[7]+"'":"'").append(",phone1='").append(strs.length>=1?strs[0]+"'":"'").append(",phone2=('" + (strs.length >= 7? strs[6]:"")+"'+'").append(strs.length >= 12 ? (!strs[6].equals("")&&!strs[11].equals("")?" "+strs[11]:strs[11]) + "'":"'").append(") where contactType ='customer' and contactUuid='").append(strs.length>=2?strs[1]+"'":"'").append(";\n");
						strsB.append("update " + (dbName) + ".dbo.com_contact set name='").append(strs.length>=8?strs[7].replace(" ","").trim()+"'":"'").append(",phone1='").append(strs.length>=1?strs[0].replace(" ","").trim()+"'":"'").append(",phone2=('" + (strs.length >= 12? strs[11].replace(" ","").trim()+"'":"'")).append(") where contactType ='customer' and contactUuid='").append(strs.length>=6?strs[1]+strs[5]+"'":"'").append(";\n");
					}
					strListContacts.append(strsB);
				}
			}
			writeTxt(toFileName, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}


	/*转换南昌齐家的房源文件
	* @author chains
	* */
	public static void transformNanChangQiJiaPropertyFile(String fromFileName,String toFileName){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").replace(" ","").trim().split(",");
					StringBuffer strsB=new StringBuffer("");
					String propertyUuid=strs.length>0?strs[0]:"";
					String propertyStatus=strs.length>1?strs[1]:"";
					String propertyEmployeeUuid1=strs.length>2?strs[2]:"";
					String propertyEmployeeUuid2=strs.length>9?strs[9]:"";
					String propertyEmployeeUuid3=strs.length>7?strs[7]:"";
					String propertyPhone1=strs.length>4?strs[4]:"";
					String propertyPhone2=strs.length>5?strs[5]:"";
					if(strs!=null&&strs.length>0){
						strsB.append("update " + "" + "dbo.pro_property set tradeStatus='").append(propertyStatus).append("',employeeId1=(select top 1 oe1.employeeId from org_employee oe1 with (nolock) where oe1.employeeUuid='" + (propertyEmployeeUuid1) + "')," + ("employeeId2=(select top 1 oe1.employeeId from org_employee oe1 with (nolock) where oe1.employeeUuid='"+(propertyEmployeeUuid2)+"'),")+ ("employeeId3=(select top 1 oe1.employeeId from org_employee oe1 with (nolock) where oe1.employeeUuid='"+(propertyEmployeeUuid3)+"')")+" where propertyUuid='").append(propertyUuid+"'").append(";\n");
						strsB.append("update com_contact set phone1='"+propertyPhone1+"',phone2='"+propertyPhone2+"' where contactType='owner' and businessId=(select top 1 pp.propertyId from pro_property pp with (nolock) where pp.propertyUuid='"+(propertyUuid)+"')").append(";\n");
					}
					strListContacts.append(strsB);
				}
			}
			writeTxt(toFileName, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}


	/*转换房友v12系列的房源联系号码解密文件
	* @author chains
	* */
	public static void transformFyV12PropertyFile(String fromFileName,String toFileName){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").replace(" ","").trim().split(",");
					StringBuffer strsB=new StringBuffer("");
					String propertyUuid=strs.length>0?strs[0]:"";
					//String propertyNo=strs.length>1?strs[1]:"";
					String propertyPhone1=strs.length>2?strs[2]:"";
					String propertyPhone2=strs.length>3?strs[3]:"";
					if(strs!=null&&strs.length>0){
						strsB.append("update com_contact set phone1='"+propertyPhone1+"',phone2='"+propertyPhone2+"',isDecodeFy='1' where contactType='owner' and businessId=(select top 1 pp.propertyId from pro_property pp with (nolock) where pp.propertyUuid='"+(propertyUuid)+"')").append(" and isDecodeFy is null;\n");
					}
					strListContacts.append(strsB);
				}
			}
			writeTxt(toFileName, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}


	/*转换常贸地产Z3区房源文件
	* @author chains
	* */
	public static void transformChangMaoDiChanPropertyFile(String fromFileName,String toFileName){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").replace(" ","").trim().split(",");
					StringBuffer strsB=new StringBuffer("");
					String custName=strs.length>0?strs[0]:"";//客源客户姓名
					String custPhone1=strs.length>1?strs[1]:"";//客源客户电话
					if(strs!=null&&strs.length>0){
						strsB.append("declare @curCustomerUuid nvarchar(200)=SUBSTRING(replace(CAST(newId() as nvarchar(100)),'-',''),1,20);\n");
						strsB.append("insert into pro_customer([customerNo],[customerUuid],[deleted],recycle,employeeId1,[createdUserId],[createdTime],lastFollowDate,[address],privy,tradeType,tradeStatus) values('',@curCustomerUuid,'0','0','-1','-1',getDate(),getDate(),'','0','求购','有效');\n");
						strsB.append("INSERT INTO pro_intentionaddress([customerId],[districtId],[areaId],[address],[deleted],[createdUserId],[createdTime]) values((select top 1 pc.customerId from pro_customer pc with (nolock) where pc.customerUuid=@curCustomerUuid),null,null,null,'0',-1,GETDATE());\n");
						strsB.append("INSERT INTO [com_contact](contactUuid,[contactType],[businessId],[name],[idType],[idNo],[phone1],[phoneType1],[phone2],[phoneType2],[remark],[encrypted],[deleted],[createdUserId],[createdTime])select SUBSTRING(replace(CAST(newId() as nvarchar(100)),'-',''),1,20),'customer',(select top 1 pc.customerId from pro_customer pc with (nolock) where pc.customerUuid=@curCustomerUuid),'"+(custName)+"','idCard' as idType,'' as idNo,'"+(custPhone1)+"' ,'mobile','','','',0 as [encrypted],'0' as deleted,'-1',GETDATE();\n");
						strsB.append("go\n");
					}
					strListContacts.append(strsB);
				}
			}
			strListContacts.append("declare @curDeptId1 Integer=-1,@curEmployeeId1 Integer=-1;\n");
			strListContacts.append("select @curDeptId1=oe.deptId,@curEmployeeId1=oe.employeeId from org_employee oe with (nolock) where oe.name ='公共账号' and oe.deleted='0' and oe.[status]!='离职';\n");
			strListContacts.append("update pc set pc.deptId1=@curDeptId1,pc.employeeId1=@curEmployeeId1 from pro_customer pc with (nolock) where pc.employeeId1=-1;\n");
			strListContacts.append("go\n");
			writeTxt(toFileName, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}


	/*转换常贸地产Z3区房源文件
	* @author chains
	* */
	public static void transformChangMaoDiChanPropertyFile1(String fromFileName,String toFilePath){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			validateFolder(toFilePath);
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").replace(" ","").trim().split(",");
					StringBuffer strsB=new StringBuffer("");
					String custName=strs.length>0?strs[0]:"";//客源客户姓名
					String custPhone1=strs.length>1?strs[1]:"";//客源客户电话
					if(strs!=null&&strs.length>0){
						strsB.append("declare @curCustomerUuid nvarchar(200)=SUBSTRING(replace(CAST(newId() as nvarchar(100)),'-',''),1,20);\n");
						strsB.append("insert into pro_customer([customerNo],[customerUuid],[deleted],recycle,employeeId1,[createdUserId],[createdTime],lastFollowDate,[address],privy,tradeType,tradeStatus) values('',@curCustomerUuid,'0','0','-1','-1',getDate(),getDate(),'','0','求购','有效');\n");
						strsB.append("INSERT INTO pro_intentionaddress([customerId],[districtId],[areaId],[address],[deleted],[createdUserId],[createdTime]) values((select top 1 pc.customerId from pro_customer pc with (nolock) where pc.customerUuid=@curCustomerUuid),null,null,null,'0',-1,GETDATE());\n");
						strsB.append("INSERT INTO [com_contact](contactUuid,[contactType],[businessId],[name],[idType],[idNo],[phone1],[phoneType1],[phone2],[phoneType2],[remark],[encrypted],[deleted],[createdUserId],[createdTime])select SUBSTRING(replace(CAST(newId() as nvarchar(100)),'-',''),1,20),'customer',(select top 1 pc.customerId from pro_customer pc with (nolock) where pc.customerUuid=@curCustomerUuid),'"+(custName)+"','idCard' as idType,'' as idNo,'"+(custPhone1)+"' ,'mobile','','','',0 as [encrypted],'0' as deleted,'-1',GETDATE();\n");
						strsB.append("go\n");
					}
					strListContacts.append(strsB);
                    if((i+1)%10000==0||i==listContacts.size()-1){
						String fileName=(i-9999+1)+"_"+(i+1)+".sql";
						writeTxt(toFilePath+"/"+fileName, strListContacts.toString());
						strListContacts.setLength(0);
					}
				}
			}

			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}

	/*转换房友v12系列的的客源联系号码解密文件
	* @author chains
	* */
	public static void transformFyV12CustomerFile(String fromFileName,String toFilePath){
		try{
			List<String> listContacts=readTxt(new File(fromFileName));
			StringBuffer strListContacts=new StringBuffer("");
			if(listContacts!=null&&listContacts.size()>0){
				for(int i=0;i<listContacts.size();i++){
					String[] strs=listContacts.get(i).replace("'","").replace(";","").replace(" ","").trim().split(",");
					StringBuffer strsB=new StringBuffer("");
					String customerUuid=strs.length>0?strs[0]:"";
					//String customerNo=strs.length>1?strs[1]:"";
					String customerPhone1=strs.length>2?strs[2]:"";
					String customerPhone2=strs.length>3?strs[3]:"";
					if(strs!=null&&strs.length>0){
						strsB.append("update com_contact set phone1='"+customerPhone1+"',phone2='"+customerPhone2+"',isDecodeFy='1' where contactType='customer' and businessId=(select top 1 pp.customerId from pro_customer pp with (nolock) where pp.customerUuid='"+(customerUuid)+"')").append(" and isDecodeFy is null;\n");
					}
					strListContacts.append(strsB);
				}
			}
			writeTxt(toFilePath, strListContacts.toString());
			System.err.println("transform succeed");
		}catch (Exception e){
			System.err.println("transform error");
			e.printStackTrace();
		}
	}

	/**
	 * 执行初始化的sql
	 * @author chains
	 * */
	public void executeInitSql(String folderPath){
		File folder = new File(folderPath);
		// 获取这个目录下的所有文件
		File[] files = folder.listFiles();
		List<String> sprintVersions=new ArrayList<String>();//需要执行的sprint的版本集合
		Map<String,File> sprintFiles=new HashMap<String,File>();//需要执行的sprint的文件集合
		// 遍历文件并处理
		for (File file : files) {
			String[] crFileNameSpitChars=file.getName().replace(".sql","").split("_");
			String sprintVersion=crFileNameSpitChars[crFileNameSpitChars.length-1];
			Pattern pattern = Pattern.compile("[0-9]*");
			if(file.isFile()&&file.getName().endsWith(".sql")&&pattern.matcher(sprintVersion).matches()==Boolean.TRUE){
				//	System.out.println(file.getName());
				//System.out.println(sprintVersion);
				sprintVersions.add(sprintVersion);
				sprintFiles.put(sprintVersion,file);
			}
		}
		//System.out.println("------------------");
		Collections.sort(sprintVersions);
		for(String sprintVersion:sprintVersions){
			System.out.println(sprintVersion);
		}
		//	System.out.println("-------------------------------------------");
		//执行sql
		for(String sprintVersion:sprintVersions){
			File curSprintFile=sprintFiles.get(sprintVersion);
			//	System.out.println(curSprintFile.getAbsolutePath());
			//curSprintFile.get
			String curSprintFileAllSql=FileUtil.getContentByFileName(curSprintFile.getAbsolutePath());
			///\s(GO)\s|\s(go)\s|\s(Go)\s|\s(gO)\s
			String[] curSprintSqls=curSprintFileAllSql.split("\\s(GO)\\s|\\s(go)\\s|\\s(Go)\\s|\\s(gO)\\s");
			for(String curSprintSql:curSprintSqls){
				System.out.println("----------------------------------------------");
				//System.out.println(curSprintSql.trim().replace(" ",""));
				System.out.println(curSprintSql.trim());
				//不是ddl语句就执行
				if(!curSprintSql.toLowerCase().trim().replace(" ","").contains("createtable")&&!curSprintSql.toLowerCase().trim().replace(" ","").contains("altertable")){
					//
				}
			}
		}
	}



	public static void main(String[] param){
		//transformFjtOwnerOrCustomerFile("fxt_web_chengjiadichan", "d:\\key_cr33510.txt", "d:\\sql_01.txt");
		//transformFjtNonOwnerFile("fxt_web_chengjiadichan", "d:\\key_cr914.txt", "d:\\sql_02.txt");
		//transformNanChangQiJiaPropertyFile("d:\\qj0805.csv", "d:\\sql_qijia.txt");
		//transformFyV12PropertyFile("d:\\gpfy-1014.CSV", "d:\\sql_p01.txt");
		//transformFyV12CustomerFile("d:\\gpky-1014.CSV", "d:\\sql_k01.txt");
		//transformFjdsOwnerFile("fxt_web_pingyidichan","d:\\pro_con.csv","d:\\pro_con_01.sql");
		//transformFjtNonOwnerFile("fxt_web_shgaodadichan", "d:\\key_cr3918.txt", "d:\\shgaodadichan_02.txt");
		//transformFjtNonOwnerFile("fxt_web_shyichengfangchan", "d:\\key_cr314.txt", "d:\\shyichengfangchan_02.txt");
	//	transformChangMaoDiChanPropertyFile1("d:\\cmdcZ3.csv","d:/aa");
		//transformFjdsOwnerFile("fxt_web_huimindichan", "d:\\property_con_huimin.csv", "d:\\sql_01.txt");
		//transformFjdsCustomerFile("fxt_web_huimindichan", "d:\\inquiry_con_huimin.csv", "d:\\sql_02.txt");
		//transformFjdsOwnerFile
	/*	transformFjdsOwnerFile("fxt_web_shxinhefangdichanjin", "d:\\property_conxinhe.csv", "d:\\sql_01.txt");
		transformFjdsCustomerFile("fxt_web_shxinhefangdichanjin", "d:\\inquiry_conxinhe.csv", "d:\\sql_02.txt");*/

	/*	Integer a=1000,b=1000;
		Integer x=100,y=100;
		System.err.println(a==b);
		System.err.println(x==y);*/

		//File sourceFile=new File("d:\\a01.txt");
		//File destFile=new File("D:\\abc\\abc1\\b.txt");
		//FileUtil.fileChannelCopy(sourceFile,destFile);
		//String aa=getContentByFileName("d:\\1_sprint1-30_create_table.sql");
		//System.err.println(aa.replace("go\n","GO\n"));
		//String [] aaStrings=aa.replace("go\n","GO\n").split("GO\n");
		//System.out.println(aaStrings.length);
		//for(int i=0;i<aaStrings.length;i++){
		//	System.out.println(i+":"+aaStrings[i]);
		//}
		String t  = LocalDate.now()+"";
		System.out.println("ttt=="+t);

		writeFile(new File("d:/1/a.txt"),"1233","utf-8");
//		File f = findFileByFileName("D:\\target","ff");
//		System.out.println("f文件的路径："+f.getAbsolutePath());

	}

	/**
	 * 创建文件目录
	 */
	public static void writeFileFolder(File targetPath){
		try {
			if(!targetPath.exists()){
				targetPath.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static final int BUFSIZE = 1024 * 8;
	public static void mergeFiles(String outFile, File[] files) {
		FileChannel outChannel = null;
		try {
			outChannel = new FileOutputStream(outFile,true).getChannel();
			for(File f : files){
				FileChannel fc = new FileInputStream(f).getChannel();
				ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);
				while(fc.read(bb) != -1){
					bb.flip();
					outChannel.write(bb);
					bb.clear();
				}
				fc.close();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {if (outChannel != null) {outChannel.close();}} catch (IOException ignore) {}
		}
	}

	/**
	 * 写文件
	 * @param f
	 * @param content
	 */
	public static void writeFile(File f,String content,String encode){
		try {
			File targetPath = new File(f.getParent());
			if(!targetPath.exists()){
				targetPath.mkdirs();
			}
			if (!f.exists()) {
				f.createNewFile();
			}
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f,false),encode);
			BufferedWriter utput = new BufferedWriter(osw);
			utput.write(content);
			utput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 方法三：比较准确，解决了实际问题
	 * @param filePath
	 * @return
	 */
	public static String getFileEncode(String filePath) {
//		String charsetName = null;
//		try {
//			File file = new File(filePath);
//			CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
//			detector.add(new ParsingDetector(false));
//			detector.add(JChardetFacade.getInstance());
//			detector.add(ASCIIDetector.getInstance());
//			detector.add(UnicodeDetector.getInstance());
//			java.nio.charset.Charset charset = null;
//			charset = detector.detectCodepage(file.toURI().toURL());
//			if (charset != null) {
//				charsetName = charset.name();
//			} else {
//				charsetName = UTF8;
//			}
//		} catch (Exception ex) {
//			ex.printStackTrace();
//			return null;
//		}
//		return charsetName;
		return "";
	}

	/**
	 * 方法三：比较准确，解决了实际问题
	 * @return
	 */
	public static String getFileEncode(File file) {
//		long start = System.currentTimeMillis();
//		String charsetName = null;
//		try {
//			CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
//			detector.add(new ParsingDetector(false));
//			detector.add(JChardetFacade.getInstance());
//			detector.add(ASCIIDetector.getInstance());
//			detector.add(UnicodeDetector.getInstance());
//			java.nio.charset.Charset charset = null;
//			charset = detector.detectCodepage(file.toURI().toURL());
//			if (charset != null) {
//				charsetName = charset.name();
//			} else {
//				charsetName = UTF8;
//			}
//		} catch (Exception ex) {
//			ex.printStackTrace();
//			return null;
//		}
		//System.out.println("file name:"+file.getName()+",charsetName:"+charsetName+",cost time=="+(System.currentTimeMillis()-start)+",ms");
	//	return charsetName;
		return "";
	}
}

